<template slot-scope="scope">
  <div>
    <!-- 表格和分页部分 -->
    <el-row class="mt-10">
      <el-col :span="24">
        <el-card>
          <el-form :inline="true" :model="searchForm">
            <el-form-item>
              <el-button type="success" @click="handleAdd()">新增</el-button>
            </el-form-item>
          </el-form>
          <el-table :data="pageData.list" border>
            <el-table-column prop="id" label="编号" width="60"></el-table-column>
            <el-table-column prop="account" label="账号" width="120" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="realName" label="真实姓名" width="120" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="birthday" label="出生日期" width="120"></el-table-column>
            <el-table-column prop="phone" label="手机号码" width="120" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column prop="address" label="用户地址" width="120" :show-overflow-tooltip="true"></el-table-column>
            <el-table-column label="操作" width="200">
              <template slot-scope="scope">
                <el-button size="mini" type="success" @click="handleEdit(scope.row.id)">修改</el-button>
                <el-button size="mini" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination
            class="mt-10"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="pageData.pageNo"
            :page-size="pageData.pageSize"
            layout="total, prev, pager, next, jumper"
            :total="pageData.totalCount"
          ></el-pagination>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      :title="(saveForm.id == '' ? '新增' : '编辑') + '用户信息'"
      :visible.sync="saveDialogVisible"
    >
      <!-- 表单数据绑定到 saveForm 对象 -->
      <el-form :model="saveForm" :rules="rules" ref="saveForm">
        <!-- 分类 ID 不显示，修改才需要分类 ID -->
        <el-form-item label="用户ID" label-width="120px" v-show="false">
          <!-- ID 设置为隐藏域 -->
          <el-input type="hidden" v-model="saveForm.id" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户账号" label-width="120px" prop="account">
          <el-input v-model="saveForm.account" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="真实姓名" label-width="120px" prop="realName">
          <el-input v-model="saveForm.realName" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" label-width="120px" prop="phone">
          <el-input v-model="saveForm.phone" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="用户地址" label-width="120px" prop="address">
          <el-input v-model="saveForm.address" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="出生日期" label-width="120px" prop="birthday">
          <el-date-picker
            type="date"
            placeholder="选择日期"
            v-model="saveForm.birthday"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="saveDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import qs from "qs";
import axios from "axios";

export default {
  data() {
    return {
      searchForm: {
        pageSize: 5, // 默认每页显示 5 条记录，与后端保持一致
        pageNo: 1
      },
      pageData: {
        list: [],
        // 当前页码
        pageNo: 1,
        // 当页显示数据
        pageSize: 5,
        totalCount: 0,
        totalPage: 0
      },
      // 保存新增对话框的显示状态
      saveDialogVisible: false,
      saveForm: {
        id: "",
        account: "",
        realName: "",
        password: "",
        sex: "",
        birthday: "",
        phone: "",
        address: ""
      },
      rules: {
        account: [
          { required: true, message: '用户账号不能为空', trigger: 'blur' }
        ],
        realName: [
          { required: true, message: '真实姓名不能为空', trigger: 'blur' }
        ],
        phone: [
          { required: true, message: '手机号码不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
        ],
        address: [
          { required: true, message: '用户地址不能为空', trigger: 'blur' }
        ],
        birthday: [
          { required: true, message: '出生日期不能为空', trigger: 'change' }
        ]
      }
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    handleDelete(id) {
      this.$confirm("此操作将永久删除该记录, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
      .then(() => {
        this.$axios.get("/user/delete?id=" + id).then(response => {
          this.$message.success("删除成功");
          this.fetchData();
        });
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    handleEdit(id) {
      this.saveDialogVisible = true;
      this.$axios
        .get("/user/view?id=" + id)
        .then(response => {
          this.saveForm = response.data;
          this.saveDialogVisible = true;
        });
    },
    doSave(saveForm) {
      let queryStr = qs.parse(qs.stringify(this.saveForm));
      console.log("发送给后端的数据：", queryStr);
      if (this.saveForm.id == "" || this.saveForm.id == null) {
        this.$axios.post("/user/add", queryStr).then(response => {
          this.saveDialogVisible = false;
          this.$message.success("添加成功");
          this.fetchData();
        });
      } else {
        this.$axios
          .post("/user/update", queryStr)
          .then(response => {
            this.saveDialogVisible = false;
            this.$message.success("修改成功");
            this.fetchData();
          });
      }
    },
    handleAdd() {
      this.saveForm = {
        id: "",
        account: "",
        realName: "",
        password: "",
        sex: "",
        birthday: "",
        phone: "",
        address: ""
      };
      this.saveDialogVisible = true;
    },
    async fetchData() {
      try {
        const response = await axios.get("/user/list", {
          params: {
            pageNo: this.pageData.pageNo,
            pageSize: this.pageData.pageSize
          }
        });
        const { list, totalCount } = response.data;
        this.pageData.list = list;
        this.pageData.totalCount = totalCount;
        this.pageData.totalPage = Math.ceil(
          totalCount / this.pageData.pageSize
        );
      } catch (error) {
        console.error("Error fetching data:", error);
      }
    },
    handleSizeChange(newSize) {
      this.pageData.pageSize = newSize;
      this.fetchData(); // 重新获取数据
    },
    handleCurrentChange(newPage) {
      this.pageData.pageNo = newPage;
      this.fetchData(); // 重新获取数据
    },
    submitForm() {
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.doSave(this.saveForm);
        } else {
          this.$message.error('表单信息填写不完整或有误，请检查！');
          return false;
        }
      });
    }
  }
};
</script>

<style>
</style>
